#include "utils/glog_adapter.h"

namespace chelper {
namespace utils {

void GlogInit(char *arg) {
    if (glog_status) {
        return;
    }

    // Initialize Google’s logging library.
    google::InitGoogleLogging(arg, &CustomPrefix);

    // record status
    glog_status = true;

    // print log in terminal and logfiles
    FLAGS_alsologtostderr = true;

    // log files folder
    std::string path;
    if (mkLogDir(getCurrentDirName(), path)) {
        FLAGS_log_dir = path;
    }

    // show color log
    FLAGS_colorlogtostderr = true;

    // disable log prefix
    // FLAGS_log_prefix = false;
}

void GlogShutDown() {
    if (glog_status) {
        google::ShutdownGoogleLogging();
    }
}

void CustomPrefix(std::ostream &os, const LogMessageInfo &info, void *) {
    os << "[" << info.severity << "]" << ' ' << "[" << info.filename << ':' << info.line_number << "]";
}

std::string getCurrentDirName() {
    std::string path = get_current_dir_name();
    return path;
}

bool mkLogDir(std::string path, std::string &logDir) {
    logDir = path + "/logFiles";
    if (access(logDir.c_str(), F_OK) == 0) {
        return true;
    }
    int ret = mkdir(logDir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
    if (ret != 0) {
        return false;
    }
    return true;
}

}  // namespace utils
}  // namespace chelper
